package development.app;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.Sprite;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.component.GridMenu;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.Utils;
import development.bean.Category;
import development.bean.SMSServiceCommand;
import development.bean.Subscription;
import development.group.FrmGroup18Plus;
import development.group.FrmGroupCuaHang18PlusNapXu;
import development.group.FrmGroupMenu;
import development.group.FrmGroupNapXuAndExchangeGold;
import development.socket.SocketClientUtil;

public class Frm18plus extends GameForm implements EventListener, SendSMSListener {
  public static final int CATEGOGRY_REQUEST = 510;
  public static final int CATEGOGRY_RESPONSE = 511;
  public static final int CONTENT_IMAGE_REQUEST = 512;
  public static final int CONTENT_IMAGE_RESPONSE = 513;
  public static final int CONTENT_STORY_REQUEST = 514;
  public static final int CONTENT_STORY_RESPONSE = 515;
  public static final int CONTENT_CLIP_REQUEST = 516;
  public static final int CONTENT_CLIP_RESPONSE = 517;
  public static final int DOWNLOAD_CHARGING_REQUEST = 518;
  public static final int DOWNLOAD_CHARGING_RESPONSE = 519;
  public static final int CANCEL_REQUEST = 520;
  public static final int CANCEL_RESPONSE = 521;

  public static final int DY = 25;

  private static GameForm singleton;
  private ImageText text8;
  private ImageText text11;
  private int categoryIndex;
  private String type;
  private Hashtable logAction = null;
  private int currentAction;
  private int CATEGORY_IMAGE_HEIGHT;
  private Vector categoriesPath;
  private int dy;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView;

  private Vector categories;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";
  private int packageNumber;
  private int totalPackage;
  private int percent;

  private int contentStoryIndex;

  private GridMenu gridMenu;

  private static final int MAX_ITEMS_ON_A_ROW = 1;
  
  private String[] SMS_SERVICE;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new Frm18plus();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    categories = new Vector();
    logAction = new Hashtable();
    categoriesPath = new Vector();
    currentAction = 1;
    type = "category";
    contentStoryIndex = 0;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    text11.setBold(true);
    CATEGORY_IMAGE_HEIGHT = 50 + 25;
    dy = DY;

    request(CATEGOGRY_REQUEST, "");

    DrawUtils.setBottomBar(_manager, "Menu chính", null, "Trở về");
    gridMenu = new GridMenu(_manager, null, null, MAX_ITEMS_ON_A_ROW, 0, DrawUtils.getTopBarHeight(), 55, 55, this);
    gridMenu.setVisible(false);

    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty()) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (type.equals("content_image")) {
      drawContentImage(g);
    }
    if (type.equals("content_story") && !categories.isEmpty()) {
      drawContentStory(g, contentStoryIndex);
    }
    drawMenu(g);
  }

  private void drawContentStory(Graphics g, int index) {
    int textY = dy;
    Category category = (Category) categories.elementAt(index);
    text11.drawParagraph2(g, (String) category.exParam.elementAt(0), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH, DEFAULT_TEXT_X, textY, scrollBar);
    text11.drawString3(g, "", GameColor.WHITE_CODE, 0, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    scrollBar.draw(g);
  }

  private void drawContentImage(Graphics g) {
    int textY = dy;
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      g.drawImage(category.image, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
      textY = textY + category.image.getHeight() + 10;
    }
    text8.drawString3(g, "", GameColor.WHITE_CODE, 0, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    scrollBar.draw(g);
  }

  private void drawMenu(Graphics g) {
    if (percent < 100) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(percent + "%");
    }
    if (!isLoadingCompleted()) {
      DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
    } else {
      if (type.equals("content_image")) {
        DrawUtils.getBottomBar(_manager).setLabels("Menu chính", "Tải về", "Trở về");
      } else if (type.equals("content_story")) {
        DrawUtils.getBottomBar(_manager).setLabels("Menu chính", "<< " + (contentStoryIndex + 1) + "/" + categories.size() + " >>", "Trở về");
      } else {
        DrawUtils.getBottomBar(_manager).setLabels("Menu chính", "", "Trở về");
      }
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    if (type.equals("-1")) {
      Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Chưa có dữ liệu cho mục này", -1);
      return;
    } else if (type.equals("-2")) {
      Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Bạn không đủ $ để sử dụng", "dịch vụ này", "Bạn có muốn nạp $ không?" ), 100);
      return;
    }
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case CATEGOGRY_RESPONSE:
      Category category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      ByteArray btImage = mapDataPackage.getByteArray("avatarImage");
      category.image = ImageUtil.resizeImage2(GameImage.createImage(btImage, 0, btImage.len()), 50, 50);
      category.hasChild = NumberUtil.parseInt(mapDataPackage.getString("hasChild")) > 0;
      category.fee = NumberUtil.parseInt(mapDataPackage.getString("money"));
      category.downloadCount = NumberUtil.parseInt(mapDataPackage.getString("downloadCount"));
      CATEGORY_IMAGE_HEIGHT = 50;
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      gridMenu.setVerDistance(55);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      Sprite sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (gridMenu.getCurrentSelectedIndex() == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH - scrollBar._width, Global.getDefaultAvatar().getHeight() + 5);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (category1.fee > 0) {
            if (!category1.hasChild) {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            if (!type.startsWith("TRUYEN") && !type.startsWith("VD")) {
              text8.drawString3(g, category1.downloadCount + " lượt tải", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, source.getRealY() + 30, GameConstants.TOP_HCENTER_ANCHOR, scrollBar);
            }
            if (!type.startsWith("VD")) {
              text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);

          if (index == gridMenu.getNumberOfItem() - 1) {
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });

      break;
    case CONTENT_IMAGE_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.fee = NumberUtil.parseInt(mapDataPackage.getString("money"));
      btImage = mapDataPackage.getByteArray("previewImage");
      category.image = ImageUtil.resizeImage2(GameImage.createImage(btImage, 0, btImage.len()), Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT);
      category.url = mapDataPackage.getString("downloadUrl");
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      break;
    case CONTENT_STORY_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.exParam.addElement(mapDataPackage.getString("detail"));
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      _manager.enableTouchPad();
      break;
    case CONTENT_CLIP_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      btImage = mapDataPackage.getByteArray("previewImage");
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      category.url = mapDataPackage.getString("downloadUrl");
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      CATEGORY_IMAGE_HEIGHT = 50;
      categories.addElement(category);
      gridMenu.setHozDistance(category.image.getHeight() + 5);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (gridMenu.getCurrentSelectedIndex() == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH - scrollBar._width, Global.getDefaultAvatar().getHeight() + 5);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (category1.fee > 0) {
            if (!category1.hasChild) {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            if (!type.startsWith("TRUYEN") && !type.startsWith("VD")) {
              text8.drawString3(g, category1.downloadCount + " lượt tải", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, source.getRealY() + 30, GameConstants.TOP_HCENTER_ANCHOR, scrollBar);
            }
            if (!type.startsWith("VD")) {
              text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);

          if (index == gridMenu.getNumberOfItem() - 1) {
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });
      break;
    case DOWNLOAD_CHARGING_RESPONSE:
      packageNumber = 0;
      totalPackage = 0;
      SMS_SERVICE = new String[]{"VDHOT","VD BT"};
      Subscription sub = Utils.getSubcription(SMS_SERVICE[0], SMS_SERVICE[1]);
      System.out.println(sub);
      if (sub == null || sub.status == Subscription.EXPIRED) {
        SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE[0], SMS_SERVICE[1]);
        if (sms != null) {
          Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Phí dịch vụ 10 gold","Bạn đồng ý không?" ), 10000);
          return;
        }
      }
      Global.systemCanvas.getMidlet().platformRequest(((Category) categories.elementAt(0)).url);
      break;
    case CANCEL_RESPONSE:
      packageNumber = totalPackage;
      break;
    }
  }

  private String buildLogAction(int requestType, StringArray parameters) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters.len(); i++) {
      sb.append(parameters.array[i]);
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.RIGHT:
      if (type.equals("content_story")) {
        if (contentStoryIndex < categories.size() - 1) {
          contentStoryIndex++;
          dy = DY;
        }
      } else {
        if (Global.systemCanvas.frmCurrent == FrmGroup18Plus.instance()) {
          FrmGroup18Plus frmGroup18Plus = (FrmGroup18Plus) FrmGroup18Plus.instance();
          frmGroup18Plus.getMultiTab().nextTab();
        } else if (Global.systemCanvas.frmCurrent == FrmGroupCuaHang18PlusNapXu.instance()) {
          FrmGroupCuaHang18PlusNapXu.setTab(2);
        }
      }
      break;
    case Key.LEFT:
      if (type.equals("content_story")) {
        if (contentStoryIndex > 0) {
          contentStoryIndex--;
          dy = DY;
        }
      } else {
        if (Global.systemCanvas.frmCurrent == FrmGroupCuaHang18PlusNapXu.instance()) {
          FrmGroupCuaHang18PlusNapXu.setTab(0);
        }
      }
      break;
    case Key.DOWN:
      if (!categories.isEmpty()) {
        if (type.startsWith("HN") || type.startsWith("TRUYEN") || type.startsWith("VD") || type.equals("content_clip_list")) {
          if (categoryIndex < categories.size() - 1) {
            categoryIndex++;
          }
        }
      }
      if (type.startsWith("HN") || type.startsWith("TRUYEN") || type.startsWith("VD") || type.equals("content_clip_list")) {
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT + 25) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      if (type.equals("content_image")) {
        dy -= 10;
      }
      if (type.equals("content_story")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        }
      }
      break;
    case Key.UP:
      if (!categories.isEmpty()) {
        if (categoryIndex > 0) {
          categoryIndex--;
        } else if (categoryIndex == 0) {
        }
      }
      if (type.equals("content_image")) {
        dy += 10;
      }
      if (type.equals("content_story")) {
        dy += 5;
      }
      if (type.startsWith("HN") || type.startsWith("TRUYEN") || type.startsWith("VD") || type.equals("content_clip_list")) {
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      break;
    case Key.FIRE:
      process(gridMenu.getCurrentSelectedIndex());
      break;
    case Key.SOFT_LEFT:
      DataPackage dataPackage = DataPackage.createDataPackage1(CANCEL_REQUEST);
      dataPackage.putString(type);
      Global.appClient.write(dataPackage);
      Global.nextState(FrmGroupMenu.instance(), null);
      break;
    case Key.SOFT_RIGHT:
      if (isLoadingCompleted()) {
        categoryIndex = 0;
        if (currentAction > 1) {
          clearCategory();
          if (type.equals("content_story")) {
            _manager.disableTouchPad();
          }
          back();
        } else {
          parentGroup.goBack();
        }
      } else {
        packageNumber = totalPackage;
        dataPackage = DataPackage.createDataPackage1(CANCEL_REQUEST);
        dataPackage.putString(type);
        Global.appClient.write(dataPackage);
      }
      break;
    default:
      break;
    }
  }

  public void keyRepeated(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (type.equals("content_image")) {
        dy -= 10;
      }
      if (type.equals("content_story")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        }
      }
      break;
    case Key.UP:
      if (type.equals("content_image")) {
        dy += 10;
      }
      if (type.equals("content_story")) {
        if (scrollBar.canScrollDown()) {
          dy += 10;
        }
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 100 && eventType == GameAlert.YES_BUTTON) {
      FrmGroupNapXuAndExchangeGold.backForm = FrmGroup18Plus.instance();
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), null);
    }
    if (alertId == 10000 && eventType == GameAlert.YES_BUTTON) {
      SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE[0], SMS_SERVICE[1]);
      if (sms != null) {
        SMSHandler.getInstance(this).sendMsg(sms.serviceNumber, sms.command);
      }
    }
  }

  private boolean validateUserMoney(int fee) {
    if (Global.currentUser.getMoney() < fee) {
      Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Bạn không đủ $ để sử dụng", "dịch vụ này", "Bạn có muốn nạp $ không?" ), 100);
      return false;
    }
    return true;
  }

  private boolean isLoadingCompleted() {
    return packageNumber == totalPackage;
  }

  private void back() {
    currentAction--;
    contentStoryIndex = 0;
    dy = DY;
    String values = (String) logAction.get(String.valueOf(currentAction));
    StringArray requestParams = GameStringUtils.split(values, ",");
    int request = NumberUtil.parseInt(requestParams.get(0));

    // Request back
    request(request, new StringArray(new String[] { requestParams.get(1) },1));
  }

  private void clearCategory() {
    gridMenu.clearData();
    categories.removeAllElements();
    categoryIndex = 0;
    contentStoryIndex = 0;
    dy = DY;
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
  }

  private void request(int header, StringArray parameters) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters.len(); i++) {
      dataPackage.putString(parameters.array[i]);
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters));
  }

  private void request(int header, String param) {
    request(header, new StringArray(new String[] { param },1));
  }

  public void destroy() {
    text8 = null;
    categoryIndex = 0;
    contentStoryIndex = 0;
    type = null;
    logAction = null;
    currentAction = 1;
    CATEGORY_IMAGE_HEIGHT = 0;
    categoriesPath = null;
    dy = 0;
    scrollBar = null;
    textView = null;
    categories = null;
    packageNumber = 0;
    totalPackage = 0;
    percent = 0;
    gridMenu = null;
    SMS_SERVICE = null;
  }

  public void onActionPerform(Event event) {
    if (event.getSource() == gridMenu) {
      process(gridMenu.getCurrentSelectedIndex());
    }
  }

  private String[] mappingTypeToServiceCode(){
    if(type == null || type.equals("")){
      return new String[]{"GAHNDS","GA HNHOT"};
    }
    if(type.startsWith("HN")){
      return new String[]{"GAHNDS","GA HNDS"};
    }
    if(type.startsWith("TRUYEN")){
      return new String[]{"GOITRUYEN","GOI TRUYEN"};
    }
    if(type.startsWith("VD")){
      return new String[]{"VDHOT","VD BT"};
    }
    return null;
  }
  private void process(int index) {
    currentAction++;
    dy = DY;
    Category category = (Category) categories.elementAt(index);
    if (category.hasChild) {
      if (!categoriesPath.contains(category.name)) {
        categoriesPath.addElement(category.name);
      }
      request(CATEGOGRY_REQUEST, new StringArray(new String[] { category.id },1));
      clearCategory();
    } else {
      if (type.startsWith("HN")) {
        SMS_SERVICE = mappingTypeToServiceCode();
        Subscription sub = Utils.getSubcription(SMS_SERVICE[0], SMS_SERVICE[1]);
        if (sub == null || sub.status == Subscription.EXPIRED) {
          SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE[0], SMS_SERVICE[1]);
          if (sms != null) {
            //Phí dịch vụ 10 gold@@@Bạn đồng ý không?
            Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Phí dịch vụ 10 gold", "Bạn đồng ý không?" ), 10000);
            return;
          }
        }
        request(CONTENT_IMAGE_REQUEST, category.id);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        clearCategory();
      } else if (type.startsWith("TRUYEN")) {
        SMS_SERVICE = mappingTypeToServiceCode();
        Subscription sub = Utils.getSubcription(SMS_SERVICE[0], SMS_SERVICE[1]);
        if (sub == null || sub.status == Subscription.EXPIRED) {
          SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE[0], SMS_SERVICE[1]);
          if (sms != null) {
            //Phí dịch vụ 10 gold@@@Bạn đồng ý không?
            Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Phí dịch vụ 10 gold", "Bạn đồng ý không?" ), 10000);
            return;
          }
        }
        request(CONTENT_STORY_REQUEST, category.id);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        clearCategory();
        gridMenu.setVisible(false);
      } else if (type.startsWith("VD")) {
        request(CONTENT_CLIP_REQUEST, category.id);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        clearCategory();
      } else if (type.equals("content_image") || type.equals("content_clip_list")) {
        int totalMoney = 0;
        for (int i = 0; i < categories.size(); i++) {
          category = (Category) categories.elementAt(i);
          totalMoney = totalMoney + category.fee;
        }
        if (!validateUserMoney(totalMoney)) {
          return;
        }
        request(DOWNLOAD_CHARGING_REQUEST, new StringArray(new String[] { type, String.valueOf(totalMoney) },2));
      }
    }
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Đăng ký thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create2( "Đăng ký thành công", "Xin mời bạn quay lại", "trong ít phút" ));
    SocketClientUtil.createSubscription(SMS_SERVICE[0], SMS_SERVICE[1]);
  }
}
